# -*- coding: utf-8 -*-
# Copyright Š 2010 alexliyu
#
# This file is part of cntop-news.
#
# cntop-news is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cntop-news is base on Top-news-buzz ,
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cntop-news.  If not, see <http://www.gnu.org/licenses/>.

import logging

from xml.dom.minidom import parseString

from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import DownloadError

from topnewsbuzz.config import MetricConfigEntry
from topnewsbuzz.metrics import MetricBase

class Metric(MetricBase):
    
    name = 'Yahoo Inlink API'
    
    def __init__(self):
        super(Metric, self).__init__()
        appid_config = MetricConfigEntry('appid', '<insert your appid here>', 'Application ID', 'Get your Yahoo Application ID here: <a href="https://developer.apps.yahoo.com/wsregapp/">Register your application on the Yahoo! Developer Network</a>', MetricConfigEntry.INPUT_TYPE_TEXT, self)
        self.appid = appid_config.value
        self.config.append(appid_config)        

    def apply(self, news):
        # Yahoo Inlink Api metric
        url = 'http://search.yahooapis.com/SiteExplorerService/V1/inlinkData?appid=' + self.appid + '&query=' + news.url + '&results=1&omit_inlinks=domain'
        try:
            result = urlfetch.fetch(url)
        except DownloadError:
            logging.error('Could not fetch url %s' % url)
            return 0.0
        if result.status_code == 200:
            xml = parseString(result.content)
            score_string = xml.firstChild.getAttribute('totalResultsAvailable')
            if score_string != '':
                score = float(score_string)
                return score
            else:
                logging.warn('No attribute "totalResultsAvailable" in response to url %s' % url)
                return 0.0
        return 0.0
